import h5py
import numpy as np
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from .interfaces import SimulationFrame

class DataManager:
    """数据管理器，处理数据存储和加载"""
    
    def __init__(self, buffer_size: int = 100):
        self.buffer_size = buffer_size
        self.buffer: List[SimulationFrame] = []
        self.current_file: Optional[Path] = None
    
    def add_frame(self, frame: SimulationFrame):
        """添加新的仿真帧"""
        self.buffer.append(frame)
        if len(self.buffer) >= self.buffer_size:
            self._save_buffer()
    
    def _save_buffer(self):
        """将缓冲区数据保存到文件"""
        if not self.current_file:
            self.current_file = Path(f"simulation_{datetime.now():%Y%m%d_%H%M%S}.h5")
            
        with h5py.File(self.current_file, 'a') as f:
            group = f.create_group(f"frame_{len(f.keys())}")
            for i, frame in enumerate(self.buffer):
                frame_group = group.create_group(f"frame_{i}")
                frame_group.create_dataset("timestamp", data=frame.timestamp)
                # ... 保存其他数据
                
        self.buffer.clear()